<template>
  <div id="employ">
    <template>
      <!--显示信息-->
      <el-table
          ref="multipleTable"
          :data="filte.slice((currPage-1)*pageSize,currPage*pageSize)"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名"
            width="120">
        </el-table-column>
        <el-table-column
            prop="userRole"
            label="权限"
            width="120"
            show-overflow-tooltip>
        </el-table-column>

        <el-table-column
            prop="phone"
            label="联系电话"
            width="120">
        </el-table-column>
        <el-table-column
            prop="date"
            label="创建时间"
        >
        </el-table-column>
        <el-table-column
            prop="remarks"
            label="备注"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            align="right">
          <template slot="header">
            <el-input
                v-model="search"
                size="mini"
                placeholder="输入姓名搜索"/>
          </template>
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="viewDetail(scope.$index,scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="del(scope.$index)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--            分页-->
      <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currPage"
          :page-sizes="[5,10,20,50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filte.length">
      </el-pagination>

      <!--            按钮-->
      <div style="margin-top: 20px">
        <el-button type="primary" @click="AddRole">新增员工</el-button>
        <el-button type="danger" @click="del()">批量删除</el-button>
      </div>
    </template>

    <!--        编辑界面-->
    <el-dialog title="员工编辑" width="920px" :before-close="clo" class="dialog dialogAdd"
               custom-class="custom-dialog"
               :visible.sync="dialogEditVisible" :close-on-click-modal='false'>
      <el-form ref="editForm" style="margin-right: 20px;" :model="editForm" :inline="true" label-position="right"
               label-width="110px" size="mini" :rules="rule">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" :disabled="!isEdit "></el-input>
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="editForm.description" :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="editForm.account" :disabled="!userAccount"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwrod">
          <el-input type="password" v-model="editForm.passwrod" :disabled="!userAccount"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="editForm.date" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="editForm.remarks" :disabled="!isEdit"></el-input>
        </el-form-item>
        <!--角色全选复选框组件-->
        <template>
          <div>
            <el-checkbox :indeterminate="isIndeterminate"
                         :disabled="!isEdit"
                         v-model="checkAll" @change="handleCheckAllChange">全选
            </el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox v-for="(city,index) in allRole"
                         :label="city.name"
                         :key="index"
                         :disabled="!isEdit"
                         v-model="city.check"
                         @change="handlecheck(index)"
            >{{ city.name }}
            </el-checkbox>
          </div>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="editForm.state != 3">
        <el-button v-if="!isEdit" @click="formEdit" size="mini">编 辑</el-button>
        <el-button v-else @click="cancelEdit" size="mini">取消编辑</el-button>
        <el-button type="primary" @click="saveEdit('editForm')" size="mini">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>


export default {
  name: "employ",
  data() {
    return {
      employ: [],
      search: "",
      multipleSelection: [],
      isEdit: false,   // 是否编辑
      dialogEditVisible: false,  // 新增模态框
      editForm: {}, // 新增表单
      editFromClone: {},
      sub: '',
      checkAll: false, //全选状态
      allRole: [], //所有的角色
      checkedCities: [],//选中的角色
      isIndeterminate: false,
      currentPage1: 1,
      currPage: 1,
      pageSize: 5,
      userAccount: false,
      rule: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur'}
        ],
        remarks: [
          {required: true, message: '请输入备注', trigger: 'blur'},
          {min: 2, max: 300, message: '长度在 2 到 300 个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入描述', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        account: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur'}
        ],
        passwrod: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {pattern: /^1[3,4,5,6,7,8,9][0-9]{9}$/, message: '请输入正确手机号', trigger: 'blur'},
        ]
      },
    }
  },
  computed: {
    filte() {
      let employ = this.employ.filter(data => !this.search ||
          data.name.toLowerCase().includes(this.search.toLowerCase()))
      return employ
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    viewDetail(index, row) {
      this.sub = index;
      this.editFromClone = this.deepClone(row)
      this.editForm = row
      this.dialogEditVisible = true
      this.checkedCities = this.editForm.role;
      this.updateRole();
    },
    del(index) {
      this.sub = ((this.currPage - 1) * this.pageSize) + index;
      this.$confirm('此操作将永久删除该员工,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.employ = this.employ.filter(item => {
          if (this.multipleSelection.indexOf(item) == -1) {
            return item;
          }
        })
        if (index || index == 0) this.employ.splice(this.sub, 1)
        localStorage.setItem('employ', JSON.stringify(this.employ))
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        if (this.filte.slice((this.currPage - 1) * this.pageSize, this.currPage * this.pageSize).length == 0 && this.currPage > 1) {
          this.currPage -= 1;
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    AddRole() {
      this.sub = '';
      this.editForm = {};
      this.editForm.role = [];
      this.editForm.date = function () {
        let date = new Date();
        let newdate = date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
        return newdate
      }(),
          this.dialogEditVisible = true;

    },
    deepClone(target) {
      // 定义一个变量
      let result;
      // 如果当前需要深拷贝的是一个对象的话
      if (typeof target === 'object') {
        // 如果是一个数组的话
        if (Array.isArray(target)) {
          result = []; // 将result赋值为一个数组，并且执行遍历
          for (let i in target) {
            // 递归克隆数组中的每一项
            result.push(this.deepClone(target[i]))
          }
          // 判断如果当前的值是null的话；直接赋值为null
        } else if (target === null) {
          result = null;
          // 判断如果当前的值是一个RegExp对象的话，直接赋值
        } else if (target.constructor === RegExp) {
          result = target;
        } else {
          // 否则是普通对象，直接for in循环，递归赋值对象的所有值
          result = {};
          for (let i in target) {
            result[i] = this.deepClone(target[i]);
          }
        }
        // 如果不是对象的话，就是基本数据类型，那么直接赋值
      } else {
        result = target;
      }
      // 返回最终结果
      return result;
    },
    formEdit() {
      this.isEdit = true;
      if (this.sub === '') {
        this.userAccount = true
      } else {
        this.userAccount = false
      }
    },
    saveEdit(editForm) {
      this.$refs[editForm].validate((valid, err) => {
        if (valid && (this.editForm.role.length > 0)) {
          if (this.sub === '') {
            let count = true;
            for (let i = 0; i < this.employ.length; i++) {
              if (this.employ[i].account === this.editForm.account) {
                count = false;
              }
            }
            if (count == true) {
              this.set(this.editForm);
              this.dialogEditVisible = false
              this.isEdit = false
              this.userAccount = false
              this.checkedCities = [];
              this.runder();
              localStorage.setItem('employ', JSON.stringify(this.employ));
              this.$message({
                type: 'success',
                message: '新增成功'
              });
            } else {
              this.$message.error('账号已存在')
              this.dialogEditVisible = true
            }
          } else {
            this.$message({
              type: 'success',
              message: '保存成功'
            });
            this.set(this.editForm);
            this.dialogEditVisible = false
            this.isEdit = false
            this.userAccount = false
            this.checkedCities = [];
            this.runder();
            localStorage.setItem('employ', JSON.stringify(this.employ));
            this.sub = '';
          }
        } else {
          console.log(err)
          this.$message.error('请完善表单内容');
        }
      })
    },
    // 取消编辑
    cancelEdit() {
      this.editForm = this.deepClone(this.editFromClone)
      this.isEdit = false;
      if (this.sub === '') this.userAccount = false
    },
    set(arr) {
      if (this.sub > -1 && this.sub !== '') {
        this.employ.splice(this.sub, 1, arr)
      } else {
        this.employ.push(arr);
      }
    },
    handleCheckAllChange() {  //全选
      this.editForm.role = [];
      if ((this.checkAll == false) && (this.isIndeterminate == false)) {
        for (let i = 0; i < this.allRole.length; i++) {
          this.allRole[i].check = false;
        }
      } else if (this.checkAll == true) {
        this.isIndeterminate = false
        for (let i = 0; i < this.allRole.length; i++) {
          this.allRole[i].check = true;
        }
        this.editForm.role = this._.cloneDeep(this.allRole);
      }
    },
    handlecheck() { //单选
      let count = 0;
      this.editForm.role = [];
      for (let i = 0; i < this.allRole.length; i++) {
        if (this.allRole[i].check == true) {
          if (this.editForm.role.indexOf(this.allRole[i]) == -1) {
            this.editForm.role.push(this.allRole[i]);
          }
          count++
        }
      }
      if (count === this.allRole.length) {
        this.isIndeterminate = false
        this.checkAll = true
      } else if (count > 0) {
        this.isIndeterminate = true
        this.checkAll = false
      } else {
        this.isIndeterminate = false
        this.checkAll = false
      }
    },
    updateRole() {
      let temp = this.deepClone(this.allRole);
      let count = 0;
      for (let i = 0; i < temp.length; i++) {
        temp[i]['check'] = false;
      }
      for (let i = 0; i < temp.length; i++) {
        for (let j = 0; j < this.checkedCities.length; j++) {
          if ((this.checkedCities[j].name == temp[i].name)) {
            temp[i]['check'] = true;
            count++;
          }
        }
      }
      if (count === temp.length) {
        this.isIndeterminate = false
        this.checkAll = true
      } else if (count > 0) {
        this.isIndeterminate = true
        this.checkAll = false
      } else {
        this.isIndeterminate = false
        this.checkAll = false
      }
      this.allRole = temp;
    },
    runder() {
      for (let i = 0; i < this.employ.length; i++) {
        let userRole = '';
        for (let j = 0; j < this.employ[i].role.length; j++) {
          userRole += this.employ[i].role[j].name + ' ';
        }
        this.employ[i].userRole = userRole
      }
    },
    clo(done) {
      if (this.isEdit) {
        this.$confirm('内容未保存，是否退出', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          if (this.sub > -1 && this.sub != '') {
            this.employ.splice(this.sub, 1, this.editFromClone)
          }
          this.editFromClone = {};
          this.$message({
            type: 'info',
            message: '已取消保存'
          });
          this.dialogEditVisible = false
          this.isEdit = false
          this.userAccount = false
          this.sub = '';
          this.checkedCities = [];
          this.runder();
          return done()
        }).catch(() => {
          this.$message({
            type: 'success',
            message: '请继续编辑'
          });
          return done(false)
        });

      } else {
        this.editFromClone = {};
        this.dialogEditVisible = false
        this.isEdit = false
        this.sub = '';
        this.checkedCities = [];
        this.runder();
        return done()
      }

    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currPage = val;
    },
  }
  ,
  created() {
    this.allRole = JSON.parse(localStorage.getItem('roleArr'))
    this.employ = JSON.parse(localStorage.getItem('employ'))
    this.runder();
  },
  watch: {
    editForm() {
      this.updateRole();
    }
  }
}
</script>

<style scoped lang="less">
#employ {
  width: 100%;
  background-color: white;
  padding: 20px 30px;
  box-sizing: border-box;
}

.pagination {
  text-align: center;
  margin: 20px 0;
}
</style>